package com.happy.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import java.util.Set;

public class ValidationUtils {
    private static final Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static <T> void validate(T object) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if (!violations.isEmpty()) {
            StringBuilder errorMsg = new StringBuilder();
            violations.forEach(v -> errorMsg
                .append(v.getPropertyPath())
                .append(": ")
                .append(v.getMessage())
                .append("\n"));
            throw new IllegalArgumentException("校验失败: " + errorMsg);
        }
    }
}
